package com.it.common.view

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import com.it.common.utils.DateUtils
import com.it.common.utils.RxTimerTaskUtils

class TimerView(context: Context, attrs: AttributeSet?) :
    androidx.appcompat.widget.AppCompatTextView(context, attrs, 0) {
    private var playTime = 0L
    private var task = RxTimerTaskUtils()
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val timeText = DateUtils.formatHour(playTime)
        text = timeText
    }


    fun startTimer(block: (() -> Unit)? = null, totalTime: Long? = null) {
        playTime = 0L
        task.interval(1000) {
            playTime += 1
            postInvalidate()  // 使用 postInvalidate 来确保在主线程中更新 UI
            totalTime?.let {
                if (it == playTime) {
                    stopTimer()
                    block?.invoke()
                }
            }
        }

    }

    fun stopTimer() {
        task.cancel()
    }
}